// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const user = event.user;
    const res = await db.collection('user').where({
        _openid: wxContext.OPENID,
    }).get();
    // 判断数据库是否有存在用户
    if (typeof (res.data[0]) == 'undefined') {
        const result = await db.collection('user').add({
            data: {
                _openid: wxContext.OPENID,
                nickName: user.nickName,
                realName: user.realName,
                avatarUrl: user.avatarUrl,
                gender: user.gender,
                is_repair: user.is_repair,
                stuNum: user.stuNum,
                dormNum: user.dormNum,
                phone: user.phone,
                _createTime: Date.now(),
                _updateTime: Date.now(),
            }
        })
        return {
            result: result,
            _openid: wxContext.OPENID,
        }
    }  else {
        const result = await db.collection('user').where({
            _openid: wxContext.OPENID,
        }).update({
            data: {
                nickName: user.nickName,
                realName: user.realName,
                avatarUrl: user.avatarUrl,
                gender: user.gender,
                is_repair: user.is_repair,
                stuNum: user.stuNum,
                dormNum: user.dormNum,
                phone: user.phone,
                _updateTime: Date.now(),
            }
        })
        return {
            result: result,
        }
    }
}